package com.btpj.module_main.ui.project

import androidx.lifecycle.viewModelScope
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.btpj.jetpack.base.BaseListViewModel
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.jetpack.entity.ApiResult
import com.btpj.module_main.data.entity.ProjectItemSub
import com.btpj.module_main.data.remote.repository.MainRepository
import kotlinx.coroutines.launch
import java.util.*

class TabItemViewModel(private val repository: MainRepository) : BaseListViewModel<ProjectItemSub>() {

    var mId = 0

    override fun createDataSource(): DataSource<Int, ProjectItemSub> {
        return object : PageKeyedDataSource<Int, ProjectItemSub>() {
            override fun loadInitial(
                params: LoadInitialParams<Int>,
                callback: LoadInitialCallback<Int, ProjectItemSub>
            ) {
                getTabPageData(1, callback)
            }

            override fun loadAfter(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, ProjectItemSub>
            ) {
                getTabPageData(params.key, callback)
            }

            override fun loadBefore(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, ProjectItemSub>
            ) {
                callback.onResult(Collections.emptyList(), null)
            }
        }
    }

    fun getTabPageData(
        count: Int,
        callback: PageKeyedDataSource.LoadInitialCallback<Int, ProjectItemSub>
    ) {
        viewModelScope.launch {
            when (val data = repository.getTabItemPageData(count, mId)) {
                is ApiResult.Success -> callback.onResult(data.data.datas, 0, 2)
                is ApiResult.Error -> ToastUtil.showShort(data.exception.errorMsg ?: "请求失败")
            }
        }
    }

    fun getTabPageData(
        count: Int,
        callback: PageKeyedDataSource.LoadCallback<Int, ProjectItemSub>
    ) {
        viewModelScope.launch {
            when (val data = repository.getTabItemPageData(count, mId)) {
                is ApiResult.Success -> callback.onResult(data.data.datas, count + 1)
                is ApiResult.Error -> ToastUtil.showShort(data.exception.errorMsg ?: "请求失败")
            }
        }
    }
}